<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<%
    String path = request.getContextPath();
    // 获得项目完全路径（假设你的项目叫MyApp，那么获得到的地址就是 http://localhost:8080/MyApp/）:
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<head>
    <title>角色</title>
    <base href=" <%=basePath%>">
    <jsp:include page="/common/backend_common.jsp" />
    <link rel="stylesheet" href="ztree/zTreeStyle.css" type="text/css">
    <link rel="stylesheet" href="assets/css/bootstrap-duallistbox.min.css" type="text/css">
    <script type="text/javascript" src="ztree/jquery.ztree.all.min.js"></script>
    <script type="text/javascript" src="assets/js/jquery.bootstrap-duallistbox.min.js"></script>
    <style type="text/css">
        .bootstrap-duallistbox-container .moveall, .bootstrap-duallistbox-container .removeall {
            width: 50%;
        }
        .bootstrap-duallistbox-container .move, .bootstrap-duallistbox-container .remove {
            width: 49%;
        }
    </style>
</head>
<body class="no-skin" youdao="bind" style="background: white">
<input id="gritter-light" checked="" type="checkbox" class="ace ace-switch ace-switch-5"/>
<div class="page-header">
    <h1>
        角色管理
        <small>
            <i class="ace-icon fa fa-angle-double-right"></i>
            维护角色与用户, 角色与权限关系
        </small>
    </h1>
</div>
<div class="main-content-inner">
    <div class="col-sm-3">
        <div class="table-header">
            角色列表&nbsp;&nbsp;
            <a class="green" href="#">
                <i class="ace-icon fa fa-plus-circle orange bigger-130 role-add"></i>
            </a>
        </div>
        <div id="roleList"></div>
    </div>
    <div class="col-sm-9">
        <div class="tabbable" id="roleTab">
            <ul class="nav nav-tabs">
                <li class="active">
                    <a data-toggle="tab" href="#roleAclTab">
                        角色与权限
                    </a>
                </li>
                <li>
                    <a data-toggle="tab" href="#roleUserTab">
                        角色与用户
                    </a>
                </li>
            </ul>
            <div class="tab-content">
                <div id="roleAclTab" class="tab-pane fade in active">
                    <ul id="roleAclTree" class="ztree"></ul>
                    <button class="btn btn-info saveRoleAcl" type="button">
                        <i class="ace-icon fa fa-check bigger-110"></i>
                        保存
                    </button>
                </div>

                <div id="roleUserTab" class="tab-pane fade" >
                    <div class="row">
                        <div class="box1 col-md-6">待选用户列表</div>
                        <div class="box1 col-md-6">已选用户列表</div>
                    </div>
                    <select multiple="multiple" size="10" name="roleUserList" id="roleUserList" >
                    </select>
                    <div class="hr hr-16 hr-dotted"></div>
                    <button class="btn btn-info saveRoleUser" type="button">
                        <i class="ace-icon fa fa-check bigger-110"></i>
                        保存
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
<div id="dialog-role-form" style="display: none;">
    <form id="roleForm">
        <table class="table table-striped table-bordered table-hover dataTable no-footer" role="grid">
            <tr>
                <td><label for="roleName">名称</label></td>
                <td>
                    <input type="text" name="name" id="roleName" value="" class="text ui-widget-content ui-corner-all">
                    <input type="hidden" name="id" id="roleId"/>
                </td>
            </tr>
            <tr>
                <td><label for="roleStatus">状态</label></td>
                <td>
                    <select id="roleStatus" name="status" data-placeholder="状态" style="width: 150px;">
                        <option value="1">可用</option>
                        <option value="0">冻结</option>
                    </select>
                </td>
            </tr>
            <td><label for="roleRemark">备注</label></td>
            <td><textarea name="remark" id="roleRemark" class="text ui-widget-content ui-corner-all" rows="3" cols="25"></textarea></td>
            </tr>
        </table>
    </form>
</div>
<script id="roleListTemplate" type="x-tmpl-mustache">
<ol class="dd-list ">
    {{#roleList}}
        <li class="dd-item dd2-item role-name" id="role_{{id}}" href="javascript:void(0)" data-id="{{id}}">
            <div class="dd2-content" style="cursor:pointer;">
            {{name}}
            <span style="float:right;">
                <a class="green role-edit" href="#" data-id="{{id}}" >
                    <i class="ace-icon fa fa-pencil bigger-100"></i>
                </a>
                &nbsp;
                <a class="red role-delete" href="#" data-id="{{id}}" data-name="{{name}}">
                    <i class="ace-icon fa fa-trash-o bigger-100"></i>
                </a>
            </span>
            </div>
        </li>
    {{/roleList}}
</ol>
</script>

<script id="selectedUsersTemplate" type="x-tmpl-mustache">
{{#userList}}
    <option value="{{id}}" selected="selected">{{username}}</option>
{{/userList}}
</script>

<script id="unSelectedUsersTemplate" type="x-tmpl-mustache">
{{#userList}}
    <option value="{{id}}">{{username}}</option>
{{/userList}}
</script>

<script type="text/javascript">
    $(function () {
        //缓存map
        var roleMap = {};
        //最近点击角色的ID
        var lastRoleId = -1;
        var selectFirstTab = true;
        var hasMultiSelect = false;
        
        var roleListTemplate = $("#roleListTemplate").html();
        Mustache.parse(roleListTemplate);
        var selectedUsersTemplate = $("#selectedUsersTemplate").html();
        Mustache.parse(selectedUsersTemplate);
        var unSelectedUsersTemplate = $("#unSelectedUsersTemplate").html();
        Mustache.parse(unSelectedUsersTemplate);
        
        loadRoleList();

        // zTree
        <!-- 树结构相关 开始 -->
        var zTreeObj = [];
        var modulePrefix = 'm_';
        var aclPrefix = 'a_';
        var nodeMap = {};

        var setting = {
            check: {
                enable: true, //勾选框
                chkDisabledInherit: true, //
                chkboxType: {"Y": "ps", "N": "ps"}, //auto check 父节点 子节点
                autoCheckTrigger: true
            },
            data: {
                simpleData: {
                    enable: true,
                    rootPId: 0 //首层ID为0
                }
            },
            callback: {
                onClick: onClickTreeNode
            }
        };

        function onClickTreeNode(e, treeId, treeNode) { // 绑定单击事件
            var zTree = $.fn.zTree.getZTreeObj("roleAclTree");
            zTree.expandNode(treeNode);
        }

        function loadRoleList() {
            $.ajax({
                url: "sys/role/list.json",
                success: function (result) {
                    if (result.ret) {
                        //渲染数据
                        var rendered = Mustache.render(roleListTemplate, {roleList: result.data});
                        $("#roleList").html(rendered);
                        bindRoleClick();
                        //遍历放入roleMap
                        $.each(result.data, function (i, role) {
                            roleMap[role.id] = role;
                        })
                    } else {
                        showMessage("加载角色", false, result.msg);
                    }
                }
            });
        }

        function bindRoleClick() {
            //编辑
            $(".role-edit").click(function (e) {
                e.preventDefault();
                e.stopPropagation();
                var roleId = $(this).attr("data-id");
                $("#dialog-role-form").dialog({
                    model: true, //除了增加窗口之外其他不可点击
                    title: "编辑角色",
                    open: function (event, ui) {
                        $(".ui-dialog-titlebar-close", $(this).parent()).hide(); //取消自带的关闭
                        $("#roleForm")[0].reset(); //将表格清空
                        var targetRole = roleMap[roleId];
                        if(targetRole) {
                            $("#roleName").val(targetRole.name);
                            $("#roleId").val(targetRole.id);
                            $("#roleStatus").val(targetRole.status);
                            $("#roleRemark").val(targetRole.remark);
                        }
                    },
                    buttons: {
                        "更新": function (e) {
                            e.preventDefault(); //阻止默认效果
                            updateRole(false, function (data) {
                                $("#dialog-role-form").dialog("close"); //关闭窗口
                            }, function (data) {
                                showMessage("编辑角色", data.msg, false);
                            })
                        },
                        "取消": function (e) {
                            $("#dialog-role-form").dialog("close"); //关闭窗口
                        }
                    }
                });
            });
            //选中当前角色
            $(".role-name").click(function (e) {
                e.preventDefault();
                e.stopPropagation();
                var roleId = $(this).attr("data-id");
                handleAclModuleSelected(roleId);
            });
        }

        function handleAclModuleSelected(roleId) {
            if(lastRoleId != -1) {
                //去除选中样式
                var lastCurrentRole = $("#role_" + lastRoleId + " .dd2-content:first");
                lastCurrentRole.removeClass("btn-yellow");
                lastCurrentRole.removeClass("no-hover");
            }
            //增加选中样式
            var currentRole = $("#role_" + roleId + " .dd2-content:first");
            currentRole.addClass("btn-yellow");
            currentRole.addClass("no-hover");
            //缓存点击的角色ID
            lastRoleId = roleId;
            //触发元素的点击事件
            $('#roleTab a:first').trigger("click");
            if (selectFirstTab) {
                loadRoleAcl(roleId);
            }
        }
        
        function loadRoleAcl(selectedRoleId) {
            if (selectedRoleId == -1) {
                return;
            }
            $.ajax({
                url: 'sys/role/roleTree.json',
                data: {
                    roleId: selectedRoleId
                },
                type: 'POST',
                success: function (result) {
                    if (result.ret){
                        //成功结果
                        renderRoleTree(result.data);
                    }else {
                        showMessage("加载角色权限数据", result.msg, false);
                    }
                }
            })
        }

        //保存角色权限关联信息
        $(".saveRoleAcl").click(function () {
            if (lastRoleId == -1) {
                showMessage("保存角色与权限点的关系", "请先在左侧选择需要操作的角色", false);
                return;
            }
            $.ajax({
                url: "sys/role/changeAcls.json",
                data: {
                    roleId: lastRoleId,
                    aclIds: getTreeSelectedId()
                },
                type: "POST",
                success: function (result) {
                    if(result.ret) {
                        showMessage("保存角色与权限点的关系", "保存成功", true);
                    }else{
                        showMessage("保存角色与权限点的关系", result.msg, false);
                    }
                }
            });
        })

        //保存角色用户关联信息
        $(".saveRoleUser").click(function () {
            if (lastRoleId == -1) {
                showMessage("保存角色与用户的关系", "请先在左侧选择需要操作的角色", false);
                return;
            }
            $.ajax({
                url: "sys/role/changeUsers.json",
                data: {
                    roleId: lastRoleId,
                    userIds: $("#roleUserList").val() ? $("#roleUserList").val().join(",") : ""//获取数组后转换成字符串并且增加","作为元素分隔符,三目避免空指针
                },
                type: "POST",
                success: function (result) {
                    if(result.ret) {
                        showMessage("保存角色与用户的关系", "保存成功", true);
                    }else{
                        showMessage("保存角色与用户的关系", result.msg, false);
                    }
                }
            });
        })

        //获取Ztree节点ID
        function getTreeSelectedId() {
            var treeObj = $.fn.zTree.getZTreeObj("roleAclTree");
            var nodes = treeObj.getCheckedNodes(true);
            var v = "";
            for (var i = 0; i<nodes.length; i++) {
                //取出权限点的ID
                if (nodes[i].id.startsWith(aclPrefix)) {
                    v += "," + nodes[i].dataId;
                }
            }
            //去掉最开头的逗号
            return v.length > 0 ? v.substring(1) : v;
        }

        function renderRoleTree(aclModuleList) {
            zTreeObj = [];
            recursivePrepareTreeData(aclModuleList);
            //将nodeMap整合到zTree中
            for (var key in  nodeMap) {
                zTreeObj.push(nodeMap[key]);
            }
            $.fn.zTree.init($("#roleAclTree"), setting, zTreeObj);
        }

        function recursivePrepareTreeData(aclModuleList) {
            if(aclModuleList && aclModuleList.length > 0) {
                $.each(aclModuleList, function (i, aclModule) {
                    var hasChecked = false;
                    if(aclModule.aclList && aclModule.aclList) {
                        $.each(aclModule.aclList, function (i, acl) {
                            //权限点放入zTreeObj
                            zTreeObj.push({
                                id: aclPrefix + acl.id,
                                pId: modulePrefix + acl.aclModuleId,
                                name: acl.name + ((acl.type == 1) ? "(菜单)" : ""),
                                chkDisabled: !acl.hasAcl,
                                checked: acl.checked,
                                dataId: acl.id
                            });
                            if (acl.checked){
                                hasChecked = true;
                            }
                        })
                    }
                    //若有子权限模块或者权限点则放入NodeMap
                    if((aclModule.aclModuleList && aclModule.aclModuleList.length > 0)
                        || (aclModule.aclList && aclModule.aclList.length)) {
                        nodeMap[modulePrefix + aclModule.id] = {
                            id: modulePrefix + aclModule.id,
                            pId: modulePrefix + aclModule.parentId,
                            name: aclModule.name,
                            open: hasChecked //若上面有权限点则可以打开，没有则无法打开
                        };
                        //若当前权限模块可以点击，那么上层权限模块也可以点击（open:true）
                        var tempAclModule = nodeMap[modulePrefix + aclModule.id];
                        while (hasChecked && tempAclModule) {
                            nodeMap[tempAclModule.id] = {
                                id: tempAclModule.id,
                                pId: tempAclModule.pId,
                                name: tempAclModule.name,
                                open: true
                            }
                            //上一层权限模块节点
                            tempAclModule = nodeMap[tempAclModule.pId];
                        }
                    }
                    recursivePrepareTreeData(aclModule.aclModuleList);
                });
            }
        }

        $(".role-add").click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            $("#dialog-role-form").dialog({
                model: true, //除了增加窗口之外其他不可点击
                title: "新增角色",
                open: function (event, ui) {
                    $(".ui-dialog-titlebar-close", $(this).parent()).hide(); //取消自带的关闭
                    $("#roleForm")[0].reset(); //将表格清空
                },
                buttons: {
                    "添加": function (e) {
                        e.preventDefault(); //阻止默认效果
                        updateRole(true, function (data) {
                            $("#dialog-role-form").dialog("close"); //关闭窗口
                        }, function (data) {
                            showMessage("新增角色", data.msg, false);
                        })
                    },
                    "取消": function (e) {
                        $("#dialog-role-form").dialog("close"); //关闭窗口
                    }
                }
            });
        })

        //更新角色
        function updateRole(isCreate, successCallback, failCallback) {
            $.ajax({
                url : isCreate ? "sys/role/save.json" : "sys/role/update.json",
                data : $('#roleForm').serializeArray(),
                type: 'POST',
                success : function (result) {
                    if (result.ret) {
                        //成功后渲染
                        loadRoleList();
                        if (successCallback) {
                            successCallback(result);
                        }
                    } else {
                        if (failCallback) {
                            failCallback(result);
                        }
                    }
                }
            });
        }

        //用户权限关系表，用户角色关系表
        $("#roleTab a[data-toggle='tab']").on("shown.bs.tab", function (e) {
            if(lastRoleId == -1){
                showMessage("加载权限关系", "请先在左侧选择操作的角色", false);
                return;
            }
            //激活选项卡,并获取属性
            if(e.target.getAttribute("href") == "#roleAclTab") {
                selectFirstTab = true;
                loadRoleAcl(lastRoleId);
            } else {
                selectFirstTab = false;
                loadRoleUser(lastRoleId);
            }
        })

        //加载角色树
        function loadRoleUser(selectedRoleId) {
            $.ajax({
                url: "sys/role/userTree.json",
                data:{
                    roleId: selectedRoleId
                },
                type:"POST",
                success: function (result) {
                    if(result.ret){
                        var renderSelected = Mustache.render(selectedUsersTemplate,{userList:result.data.selected});
                        var renderUnSelected = Mustache.render(unSelectedUsersTemplate,{userList:result.data.unselected});
                        //为何两个渲染后的模板相加：两个模板有不同的属性“selected“
                        $("#roleUserList").html(renderSelected + renderUnSelected);
                        //box渲染
                        //第一次初始化(默认第一次为false)
                        if(!hasMultiSelect){
                            $("select[name='roleUserList']").bootstrapDualListbox({
                               showFilterInputs: false, //不过滤
                               moveOnSelect: false,
                               infoText: false
                            });
                            //第一次渲染后，则不再次初始化，每次走else里的刷新
                            hasMultiSelect = true;
                        }else {
                            //刷新
                            $("select[name='roleUserList']").bootstrapDualListbox("refresh", true);
                        }
                    }else {
                        showMessage("加载角色用户数据", result.msg, false);
                    }
                }
            })
        }

    });
</script>
</body>
</html>
